package com.artezio.buyndrive.service.impl;

import com.artezio.buyndrive.service.MD5Service;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


@Service
public class MD5ServiceImpl implements MD5Service {
    
    private final int MIN_LENGTH = 16;
    private final int MAX_LENGTH = 32;
    private static final Logger LOG =
            LoggerFactory.getLogger(MD5ServiceImpl.class);

    public String getMD5(String input) throws NoSuchAlgorithmException {
        LOG.debug("Trying to getMD5 for {}", input);
        if (input == null || input.length() == 0) {
            return "";
        }
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        String hashtext = number.toString(MIN_LENGTH);
        while (hashtext.length() < MAX_LENGTH) {
            hashtext = "0" + hashtext;
        }
        LOG.debug("Get MD5 {}", hashtext);
        return hashtext;
    }
}
